use std::collections::HashMap;
#[allow(dead_code)]
pub fn convert_base2(num_str: &str, to_base: u32) -> String {
    // TODO: 这里写逻辑
    let num_and_base: Vec<&str> = num_str
        .split(|c| c == '(' || c == ')')
        .map(|s| s.trim())
        .collect();
    // println!("num_and_base={:?},len={}", num_and_base, num_and_base.len());
    let num: Vec<char> = num_and_base[0].chars().collect();
    // .map(|&c| c - b'0')
    // .collect();
    let base = num_and_base[1].parse::<i32>().unwrap();
    let hash_char_to_digital = HashMap::from([
        ('0', 0u32),
        ('1', 1),
        ('2', 2),
        ('3', 3),
        ('4', 4),
        ('5', 5),
        ('6', 6),
        ('7', 7),
        ('8', 8),
        ('9', 9),
        ('A', 10),
        ('B', 11),
        ('C', 12),
        ('D', 13),
        ('E', 14),
        ('F', 15),
        ('a', 10),
        ('b', 11),
        ('c', 12),
        ('d', 13),
        ('e', 14),
        ('f', 15),
    ]);
    let hash_digital_to_char: HashMap<u32, char> = HashMap::from([
        (0, '0'),
        (1, '1'),
        (2, '2'),
        (3, '3'),
        (4, '4'),
        (5, '5'),
        (6, '6'),
        (7, '7'),
        (8, '8'),
        (9, '9'),
        (10, 'a'),
        (11, 'b'),
        (12, 'c'),
        (13, 'd'),
        (14, 'e'),
        (15, 'f'),
    ]);

    let mut number = 0;
    let mut base_product = 1;

    for i in num.iter().rev() {
        number += hash_char_to_digital.get(&i).unwrap() * base_product;
        base_product *= base as u32;

        // println!("i={},num={}", i, number);
    }

    let mut anwer_number: Vec<&char> = Vec::new();
    while number > 0 {
        anwer_number.push(hash_digital_to_char.get(&(number % to_base)).unwrap());
        number /= to_base;
    }
    let anwer_number: String = anwer_number.iter().map(|&&c| c).rev().collect();
    // println!("answer_number = {:?}", anwer_number);
    anwer_number
}

//参考别人的代码的改进
pub fn convert_base(num_str: &str, to_base: u32) -> String {
    let num_and_base: Vec<&str> = num_str
        .split(|c| c == '(' || c == ')')
        .filter(|c| !c.is_empty())
        .collect();

    let base = u32::from_str_radix(num_and_base[1], 10).unwrap();
    let mut num = u32::from_str_radix(num_and_base[0], base).unwrap();
    let mut ans = vec![];
    loop {
        let remainder = num % to_base;
        num = num / to_base;

        ans.push(std::char::from_digit(remainder, to_base).unwrap());
        if num == 0 {
            break;
        }
    }

    // ans.into_iter().rev().collect()
    ans.iter().rev().collect()
}
